package com.bandi.tharshesnows.pics;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.WeakHashMap;

import org.apache.http.util.ByteArrayBuffer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class PictureStorage {

  private String storageDirectoryName;
  private File storageDirectory;
  private WeakHashMap<String, Bitmap> imageCache = new WeakHashMap<String, Bitmap>();
  
  private static PictureStorage INSTANCE;
  
  public static PictureStorage getInstance(){
    if(INSTANCE==null){
      throw new IllegalStateException("Please init.");
    }
    return INSTANCE;
  }
  
  public static void init(Context context){
    if(INSTANCE==null){
      INSTANCE = new PictureStorage(context);
    }
  }

  private PictureStorage(Context context) {
    storageDirectoryName = context.getPackageName() + "/";
    storageDirectory = new File(Environment.getExternalStorageDirectory(), storageDirectoryName);
    if (!storageDirectory.exists()) {
      storageDirectory.mkdir();
      File noMedia = new File(storageDirectory, ".nomedia");
      if (!noMedia.exists())
        try {
          noMedia.createNewFile();
        }
        catch (IOException e) {
        }
    }
  }

  public void storeImage(String urlStr, String name) throws IOException {
    URL url = new URL(urlStr);
    URLConnection conn = url.openConnection();
    InputStream is = conn.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);
    ByteArrayBuffer baf = new ByteArrayBuffer(5000);
    int current = 0;
    while ((current = bis.read()) != -1) {
      baf.append((byte) current);
    }
    /* Convert the Bytes read to a String. */
    File f = new File(storageDirectory, name);
    if (f.exists()) {
      f.delete();
    }
    FileOutputStream fos = new FileOutputStream(f);
    fos.write(baf.toByteArray());
    fos.flush();
    fos.close();
  }

  public Bitmap getImage(String name) {
    if (imageCache.containsKey(name)) {
      return imageCache.get(name);
    }
    File f = new File(storageDirectory, name);
    if (!f.exists()) {
      return null;
    }
    Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
    imageCache.put(name, bitmap);
    return bitmap;
  }
  

}
